<template>
  <div class="model-test">
    <a-row :gutter="20">
      <a-col :span="24">
        <a-card>
          <template #title>
            <div class="card-header">
              <ApiOutlined />
              <span>模型测试</span>
            </div>
          </template>
          
          <a-tabs v-model:activeKey="activeTab">
            <a-tab-pane key="adapters" tab="适配器管理">
              <div class="adapters-section">
                <a-row :gutter="16">
                  <a-col :span="12">
                    <a-card title="适配器列表" size="small">
                      <a-list
                        :data-source="adapters"
                        :loading="adaptersLoading"
                      >
                        <template #renderItem="{ item }">
                          <a-list-item>
                            <a-list-item-meta>
                              <template #avatar>
                                <a-avatar :style="{ backgroundColor: getAdapterColor(item.industry) }">
                                  {{ item.industry.charAt(0).toUpperCase() }}
                                </a-avatar>
                              </template>
                              <template #title>
                                <a-tag :color="item.status === 'active' ? 'green' : 'red'">
                                  {{ item.status === 'active' ? '已激活' : '未激活' }}
                                </a-tag>
                                {{ item.name }}
                              </template>
                              <template #description>
                                支持行业: {{ item.industry }} | 版本: {{ item.version }}
                              </template>
                            </a-list-item-meta>
                            <template #actions>
                              <a-button 
                                type="link" 
                                size="small"
                                @click="testAdapter(item)"
                                :loading="item.testing"
                              >
                                测试
                              </a-button>
                              <a-button 
                                type="link" 
                                size="small"
                                @click="viewAdapterDetails(item)"
                              >
                                详情
                              </a-button>
                            </template>
                          </a-list-item>
                        </template>
                      </a-list>
                    </a-card>
                  </a-col>
                  
                  <a-col :span="12">
                    <a-card title="适配器详情" size="small">
                      <div v-if="selectedAdapter">
                        <a-descriptions :column="1" bordered>
                          <a-descriptions-item label="适配器名称">
                            {{ selectedAdapter.name }}
                          </a-descriptions-item>
                          <a-descriptions-item label="支持行业">
                            {{ selectedAdapter.industry }}
                          </a-descriptions-item>
                          <a-descriptions-item label="版本">
                            {{ selectedAdapter.version }}
                          </a-descriptions-item>
                          <a-descriptions-item label="状态">
                            <a-tag :color="selectedAdapter.status === 'active' ? 'green' : 'red'">
                              {{ selectedAdapter.status === 'active' ? '已激活' : '未激活' }}
                            </a-tag>
                          </a-descriptions-item>
                          <a-descriptions-item label="描述">
                            {{ selectedAdapter.description || '暂无描述' }}
                          </a-descriptions-item>
                        </a-descriptions>
                      </div>
                      <a-empty v-else description="请选择一个适配器查看详情" />
                    </a-card>
                  </a-col>
                </a-row>
              </div>
            </a-tab-pane>
            
            <a-tab-pane key="transform" tab="模型转换">
              <div class="transform-section">
                <a-row :gutter="16">
                  <a-col :span="12">
                    <a-card title="转换配置" size="small">
                      <a-form layout="vertical">
                        <a-form-item label="源数据">
                          <a-textarea
                            v-model:value="sourceData"
                            :rows="8"
                            placeholder="请输入源数据JSON..."
                          />
                        </a-form-item>
                        
                        <a-form-item label="目标行业">
                          <a-select v-model:value="targetIndustry" placeholder="请选择目标行业">
                            <a-select-option value="automotive">汽车制造</a-select-option>
                            <a-select-option value="electronics">电子制造</a-select-option>
                            <a-select-option value="chemical">化工制造</a-select-option>
                          </a-select>
                        </a-form-item>
                        
                        <a-form-item>
                          <a-space>
                            <a-button type="primary" @click="testTransform" :loading="transformLoading">
                              <PlayCircleOutlined />
                              执行转换
                            </a-button>
                            <a-button @click="clearTransformData">
                              <ClearOutlined />
                              清空数据
                            </a-button>
                          </a-space>
                        </a-form-item>
                      </a-form>
                    </a-card>
                  </a-col>
                  
                  <a-col :span="12">
                    <a-card title="转换结果" size="small">
                      <div v-if="transformResult">
                        <a-descriptions :column="1" bordered>
                          <a-descriptions-item label="转换状态">
                            <a-tag :color="transformResult.success ? 'success' : 'error'">
                              {{ transformResult.success ? '成功' : '失败' }}
                            </a-tag>
                          </a-descriptions-item>
                          <a-descriptions-item label="转换时间">
                            {{ transformResult.duration || 0 }}ms
                          </a-descriptions-item>
                          <a-descriptions-item label="数据项数">
                            {{ transformResult.itemCount || 0 }}
                          </a-descriptions-item>
                        </a-descriptions>
                        
                        <a-divider />
                        
                        <a-form-item label="转换后的数据">
                          <a-textarea
                            :value="JSON.stringify(transformResult.data, null, 2)"
                            :rows="10"
                            readonly
                          />
                        </a-form-item>
                      </div>
                      <a-empty v-else description="暂无转换结果" />
                    </a-card>
                  </a-col>
                </a-row>
              </div>
            </a-tab-pane>
            
            <a-tab-pane key="logs" tab="测试日志">
              <div class="logs-section">
                <a-card title="测试日志" size="small">
                  <a-timeline>
                    <a-timeline-item
                      v-for="(log, index) in testLogs"
                      :key="index"
                      :color="log.type === 'success' ? 'green' : log.type === 'error' ? 'red' : 'blue'"
                    >
                      <template #dot>
                        <CheckCircleOutlined v-if="log.type === 'success'" />
                        <CloseCircleOutlined v-else-if="log.type === 'error'" />
                        <InfoCircleOutlined v-else />
                      </template>
                      <p><strong>{{ log.title }}</strong></p>
                      <p>{{ log.message }}</p>
                      <p style="color: #999; font-size: 12px;">{{ log.time }}</p>
                    </a-timeline-item>
                  </a-timeline>
                </a-card>
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { 
  ApiOutlined, 
  PlayCircleOutlined, 
  ClearOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  InfoCircleOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { apsApi } from '@/api/aps'

export default {
  name: 'ModelTest',
  components: {
    ApiOutlined,
    PlayCircleOutlined,
    ClearOutlined,
    CheckCircleOutlined,
    CloseCircleOutlined,
    InfoCircleOutlined
  },
  setup() {
    const activeTab = ref('adapters')
    const adaptersLoading = ref(false)
    const transformLoading = ref(false)
    
    const adapters = ref([])
    const selectedAdapter = ref(null)
    const sourceData = ref('')
    const targetIndustry = ref('automotive')
    const transformResult = ref(null)
    const testLogs = ref([])
    
    const addLog = (title, message, type = 'info') => {
      testLogs.value.unshift({
        title,
        message,
        type,
        time: new Date().toLocaleTimeString()
      })
    }
    
    const getAdapterColor = (industry) => {
      const colors = {
        automotive: '#1890ff',
        electronics: '#52c41a',
        chemical: '#faad14'
      }
      return colors[industry] || '#d9d9d9'
    }
    
    const loadAdapters = async () => {
      adaptersLoading.value = true
      try {
        const result = await apsApi.getAdapters()
        adapters.value = result.map(adapter => ({
          ...adapter,
          testing: false
        }))
        addLog('适配器列表', '成功加载适配器列表', 'success')
      } catch (error) {
        addLog('适配器列表', '加载适配器列表失败: ' + error.message, 'error')
        message.error('加载适配器列表失败')
      } finally {
        adaptersLoading.value = false
      }
    }
    
    const testAdapter = async (adapter) => {
      adapter.testing = true
      try {
        const result = await apsApi.testAdapter(adapter.name, { test: true })
        addLog(`适配器测试 - ${adapter.name}`, '测试成功', 'success')
        message.success(`${adapter.name} 适配器测试成功`)
      } catch (error) {
        addLog(`适配器测试 - ${adapter.name}`, '测试失败: ' + error.message, 'error')
        message.error(`${adapter.name} 适配器测试失败`)
      } finally {
        adapter.testing = false
      }
    }
    
    const viewAdapterDetails = (adapter) => {
      selectedAdapter.value = adapter
    }
    
    const testTransform = async () => {
      if (!sourceData.value.trim()) {
        message.warning('请输入源数据')
        return
      }
      
      if (!targetIndustry.value) {
        message.warning('请选择目标行业')
        return
      }
      
      transformLoading.value = true
      try {
        const data = JSON.parse(sourceData.value)
        const startTime = Date.now()
        const result = await apsApi.testModelTransform(data, targetIndustry.value)
        const duration = Date.now() - startTime
        
        transformResult.value = {
          success: true,
          data: result,
          duration,
          itemCount: Object.keys(result).length
        }
        
        addLog('模型转换', `成功转换到 ${targetIndustry.value} 行业`, 'success')
        message.success('模型转换成功')
      } catch (error) {
        transformResult.value = {
          success: false,
          data: null,
          duration: 0,
          itemCount: 0
        }
        
        addLog('模型转换', '转换失败: ' + error.message, 'error')
        message.error('模型转换失败')
      } finally {
        transformLoading.value = false
      }
    }
    
    const clearTransformData = () => {
      sourceData.value = ''
      transformResult.value = null
      message.success('数据已清空')
    }
    
    onMounted(() => {
      loadAdapters()
    })
    
    return {
      activeTab,
      adaptersLoading,
      transformLoading,
      adapters,
      selectedAdapter,
      sourceData,
      targetIndustry,
      transformResult,
      testLogs,
      getAdapterColor,
      testAdapter,
      viewAdapterDetails,
      testTransform,
      clearTransformData
    }
  }
}
</script>

<style scoped>
.model-test {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.adapters-section,
.transform-section,
.logs-section {
  padding: 20px 0;
}
</style> 